package com.gulimall.authserver.controller;

import com.alibaba.fastjson2.JSONObject;
import com.gulimall.authserver.feign.MemberFeignService;
import com.gulimall.authserver.feign.ThreadPartFeignService;
import com.gulimall.authserver.vo.UserLoginVo;
import com.gulimall.authserver.vo.UserRegisterVo;
import com.gulimall.common.constrant.AuthServerConstant;
import com.gulimall.common.exception.BizCodeEnum;
import com.gulimall.common.utils.R;
import com.gulimall.common.vo.MemberRespVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author kkk
 * @date 2022/7/30
 */
@Controller
@Slf4j
public class LoginController {
    @Autowired
    private ThreadPartFeignService partFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/sms/sendCode")
    @ResponseBody

    public R sendCode(@RequestParam String phoneNumber) {
        ValueOperations<String, String> forValue = redisTemplate.opsForValue();
        String codeKey = AuthServerConstant.SMS_CODE_CHANE_PREFIX + phoneNumber;

        //接口防刷
        String smsCode = forValue.get(codeKey);
        if (StringUtils.hasText(smsCode)) {
            long l = Long.parseLong(smsCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        int code = new Random().nextInt(900000) + 100000;

        //将验证码存入redis中
        forValue.set(codeKey, String.valueOf(code) + "_" + System.currentTimeMillis(), 10, TimeUnit.MINUTES);
        partFeignService.sendSms(phoneNumber, String.valueOf(code));
        return R.ok();
    }

    @PostMapping("/register")
    @ResponseBody
    public R register(@Valid UserRegisterVo userRegisterVo, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            Map<String, Object> errorMap =
                    bindingResult.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField,
                            FieldError::getDefaultMessage));

            return R.error().put("errorMap", errorMap);
        }
        //校验验证码
        ValueOperations<String, String> forValue = redisTemplate.opsForValue();
        String codeKey = AuthServerConstant.SMS_CODE_CHANE_PREFIX + userRegisterVo.getPhone();
        String code = forValue.get(codeKey);
        if (StringUtils.hasText(code) || !code.split("_")[0].equals(userRegisterVo.getRegisterCode().toString())) {
            Map<String, String> param = new HashMap<>();
            param.put("registerCode", "验证码错误");
            return R.error().put("errorMap", param);
        }
        //调用远程远程服务注册
        try {
            R r = memberFeignService.registerMember(userRegisterVo);
            if (r.getResult() != 0) {
                return r;
            } else {
                redisTemplate.delete(codeKey);
            }
        } catch (Exception e) {
            log.error("远程服务调用异常 " + e.getMessage());
            return R.error();
        }

        return R.ok();
    }

    @GetMapping("login.html")
    public String login(HttpSession session) {
        if (session.getAttribute(AuthServerConstant.LOGIN_INFO) != null) {
            return "redirect:http://gulimall.com";
        }
        return "index";
    }

    @PostMapping("/login")
    @ResponseBody
    public R login(UserLoginVo loginVo, HttpSession session) {
        try {
            R r = memberFeignService.memberLogin(loginVo);
            if (r.getResult() == 0) {
                MemberRespVo memberRespVo = JSONObject.parseObject(JSONObject.toJSONString(r.get("data")),
                        MemberRespVo.class);
                session.setAttribute(AuthServerConstant.LOGIN_INFO, memberRespVo);
                return R.ok();
            } else {
                return r;
            }
        } catch (Exception e) {
            log.error("远程服务调用异常 " + e.getMessage());
            return R.error();
        }
    }
}
